<template>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: 'homepage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 搜索与添加 -->
        <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="gatuserlistst">
            <template #append>
                <el-button icon="Search" @click="gatuserlistst" />
            </template>
        </el-input>
        <el-button type="primary" @click="dialogAdd = true">添加用户</el-button>
        <!-- 用户列表 -->
        <el-table :data="userlista" style="width: 100%;margin-top: 15px;" v-if="userlista" border stripe>
            <el-table-column type="index" label="#"/>
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="mobile" label="电话" />
            <el-table-column prop="role_name" label="角色" />
            <el-table-column prop="mg_state" label="状态">
                <template #default="{ row }">
                    <el-switch v-model="row.mg_state" @change="SwitchChange(row)" />
                </template>
            </el-table-column>
            <!-- 操作按钮 -->
            <el-table-column label="操作" width="250px">
                <template #default="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button size="small" type="danger" icon="delete"
                        @click="userDelete(scope.$index, scope.row)">删除</el-button>
                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button size="small" type="warning" icon="setting" @click="setrole(scope.row)" >分配</el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum" :page-sizes="[2, 5, 10, 12]" :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="dialogAdd" title="添加用户信息" width="450" @close="addDialogClose()">
        <el-form :model="users" :rules="addFormRules" ref="usersRef">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="users.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="users.password" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="users.email" />
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="users.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogAdd = false">取消</el-button>
                <el-button type="primary" @click="adduser()">提交</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog v-model="editDialog" title="修改用户信息" width="450" @close="addlogClose()">
        <el-form :model="editfrom" :rules="addFormRules" ref="usersRefto">
            <el-form-item label="用户名">
                <el-input v-model="editfrom.username" disabled />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editfrom.email" />
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="editfrom.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="adduser_two()">确 定</el-button>
            </div>
        </template>

    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog v-model="setRight" title="分配角色" width="450" @close="setRole()">
        <div>
            <p>当前的用户：{{ userInfo.username }} </p>
            <p>当前的角色：{{ userInfo.role_name }}</p>
            <p>分配新角色：
                <el-select v-model="selectRoleId" placeholder="请选择" style="width: 200px;">
                    <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </p>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="setRight = false">取 消</el-button>
                <el-button type="primary" @click="saveRole()">确 定</el-button>
            </div>
        </template>

    </el-dialog>
</template>
<script>
import { ElMessage } from 'element-plus';

export default {
    props: [],
    data() {
        //邮箱的校验规则表达式
        var checkemail = (rule, value, call) => {
            const regEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
            if (regEmail.test(value)) {
                return call()
            }
            call(new Error('请输入合法邮箱'))
        }
        //手机号的校验规则表达式
        var checkmobile = (rule, value, call) => {
            const regmoblie = /^1(?:3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
            if (regmoblie.test(value)) {
                return call()
            }
            call(new Error('请输入合法手机号'))
        }
        return {
            userlista: null,
            total: 0,    //列表个数
            dialogAdd: false,    //控制添加用户对话框
            editDialog: false,  //控制修改用户对话框
            setRight: false,   //控制角色对话框
            editfrom: {},    //用户查询存储的数据
            userInfo: {},     //需要分配权限角色的用户信息
            rolelist: [],   //角色列表的用户信息
            selectRoleId: '',  // 已选中的角色id值
            users: {
                username: "",
                password: "",
                email: "",
                mobile: "",
            },
            //校验规则
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkemail, trigger: 'blur' },
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkmobile, trigger: 'blur' }
                ],
            },
            queryInfo: {
                query: '',
                pagenum: 1,    //当前的页数
                pagesize: 2    //当前每页显示多少条
            }
        }
    },
    methods: {
        //获取用户列表
        async gatuserlistst() {
            let res = await this.$axios.get("/users", { params: this.queryInfo });
            this.userlista = res.data.data.users
            this.total = res.data.data.total
        },
        //修改编辑用户
        async handleEdit(id) {
            // console.log(id);
            this.editDialog = true;
            const res = await this.$axios.get("users/" + id)
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: "获取成功",
                    type: 'success'
                })
                this.editfrom = res.data.data
                // console.log(this.editfrom);
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //编辑用户提交
        adduser_two() {
            this.$refs.usersRefto.validate(async valid => {     //验证表单通过才提交
                if (!valid) return
                const res = await this.$axios.put("users/" + this.editfrom.id, {
                    email: this.editfrom.email,
                    mobile: this.editfrom.mobile
                })
                if (res.data.meta.status == 200) {
                    ElMessage({
                        message: "更新成功",
                        type: 'success'
                    })
                    this.editDialog = false;   //关闭对话框
                    this.gatuserlistst()    //刷新数据列表
                } else {
                    ElMessage.error(res.data.meta.msg)
                }
            })
        },
        //根据ID删除用户
        async userDelete(index, row) {
            try {
                await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                const { data } = await this.$axios.delete("users/" + row.id);
                if (data.meta.status == 200) {
                    this.gatuserlistst();
                    this.$message({
                        message: "删除成功",
                        type: 'success'
                    })
                } else {
                    this.$message.error(data.meta.msg)
                }
            } catch (error) {
                if (error === 'cancel') {
                    this.$message.info('已取消删除')
                } else {
                    this.$message.error('删除失败')
                }
            }
        },
        //添加提交用户
        adduser() {
            this.$refs.usersRef.validate(async valid => {    //验证表单通过才提交
                if (!valid) return
                let data = await this.$axios.post("users", this.users)
                // console.log(data);
                if (data.data.meta.status == 201) {
                    ElMessage({
                        message: "创建成功",
                        type: 'success',
                    })
                    this.gatuserlistst();
                    this.dialogAdd = false
                } else {
                    ElMessage.error("创建失败" + data.data.meta.msg)
                }
            })
        },
        handleSizeChange(newSize) {       //监听pagesize改变的事件
            // console.log(newSize);
            this.queryInfo.pagesize = newSize;
            this.gatuserlistst()
        },
        handleCurrentChange(newSize) {    //监听页码值的事件
            // console.log(newSize);
            this.queryInfo.pagenum = newSize;
            this.gatuserlistst()
        },
        //更改用户状态
        async SwitchChange(userinfo) {
            // console.log(userinfo);
            const res = await this.$axios.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            // console.log(res);
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: "设置状态成功",
                    type: 'success'
                })
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //清空添加用户对话框内容
        addDialogClose() {
            this.$refs.usersRef.resetFields()
        },
        //清空编辑用户对话框
        addlogClose() {
            this.$refs.usersRefto.resetFields()
        },
        //分配权限对话框
        async setrole(userInfo) {
            this.userInfo = userInfo;
            const res = await this.$axios.get("roles")
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: "获取成功",
                    type: "success"
                })
                this.rolelist = res.data.data
                // console.log(this.rolelist);
            } else {
                ElMessage.error("res.data.meta.msg")
            }
            this.setRight = true;
        },
        //确认分配权限
        async saveRole() {
            if (!this.selectRoleId) {
                return ElMessage.error('请选择要分配的角色')
            }
            const res = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
            // console.log(res);
            if (res.data.meta.status ==200) {
                ElMessage({
                    message: "设置角色成功",
                    type:"success"
                })
                this.gatuserlistst();
                this.setRight = false
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //清空权限对话框
        setRole() {
            this.userInfo = {}
            this.selectRoleId=''
        }
    },
    mounted() {    //挂载之后调用
        this.gatuserlistst()
    }
}
</script>
<style scoped>
.el-input-group {
    width: 30%;
    margin-right: 15px;
}

.el-table {
    margin-bottom: 15px;
}
</style>